import random
from douyin.models import accounts
from utils.error_code import ErrorCode
from douyin.common import common_request
from utils.reply import reply
from lib.logger import logger


def request_comments(id: str, cookie: str, offset: int = 0, limit: int = 20, common_params: str = '') -> tuple[
    dict, bool]:
    """
    请求抖音获取评论信息
    """
    logger.info(f'开始执行request_comments方法，id: {id}, cookie: {cookie}, offset: {offset}, limit: {limit}, common_params: {common_params}')

    headers = {"cookie": cookie}
    params = {"aweme_id": id, "cursor": offset, "count": limit, "item_type": 0}
    resp, succ = common_request('/aweme/v1/web/comment/list/', params, headers, common_params)
    if not succ:
        return resp, succ
    ret = {"total": resp.get('total', 0)}
    ret["comments"] = resp.get('comments', [])

    logger.info(f'结束执行request_comments方法，id: {id}, offset: {offset}, limit: {limit}, resp: {resp}, succ: {succ}')

    return ret, succ


def douyin_comments(id: str, offset: int = 0, limit: int = 20, common_params=None):
    """
    获取视频评论
    """
    logger.info(f'开始执行douyin_comments方法，id: {id}, offset: {offset}, limit: {limit}, common_params: {common_params}')

    _accounts = accounts.load(type='douyin')
    random.shuffle(_accounts)
    for account in _accounts:
        if account.get('expired', 0) == 1:
            continue
        account_id = account.get('id', '')
        res, succ = request_comments(id, account.get('cookie', ''), offset, limit, common_params)
        if res == {} or not succ:
            logger.error(
                f'获取评论失败。账号: {account_id}, 视频id: {id}, 偏移量: {offset}, 限制数量: {limit}, 结果: {res}')
            continue
        logger.info(
            f'获取评论成功，账号: {account_id}, 视频id: {id}, 偏移量: {offset}, 限制数量: {limit}, 结果: {res}')
        return reply(ErrorCode.OK, '成功', res)

    logger.warning(f'获取评论失败。视频id: {id}, 偏移量: {offset}, 限制数量: {limit}')
    return reply(ErrorCode.NO_ACCOUNT, '请先添加账号')